const express = require("express");
const router = express.Router();
const { sequelize, User } = require("../../models");
const { Op } = require("sequelize");
const { success, failure } = require("../../utils/responses");
const {
  initOrderStream,
  broadcastOrderCount,
} = require("../../streams/count-order");

/**
 * 统计每个月用户数量
 * GET /admin/charts/user
 */
router.get("/user", async (req, res) => {
  try {
    let sql =
      "SELECT DATE_FORMAT(`createdAt`, '%Y-%m') AS `month`, COUNT(*) AS `value` FROM `Users` GROUP BY `month` ORDER BY `month` ASC";
    let [result] = await sequelize.query(sql);
    success(res, "查询每月用户数量成功。", { result });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * SSE 统计每个月订单数量
 * GET /admin/charts/stream_order
 */
router.get("/stream_order", async (req, res) => {
  //这样每来一个新连接，就初始化一个流，然后广播数据-
  // 但是是给所有用户发送数据，而不是给当前用户发送数据，影响不大，因为数据是正确的
  // 如果需要给当前用户发送数据，需要使用redis，将用户id与sse连接绑定----------
  try {
    initOrderStream(res, req);
    await broadcastOrderCount();
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
